/******************************************************************************
 * @File name   :      RoleAndFunctionController.java
 *
 * @Author      :      wangzhize
 *
 * @Date        :      2011-6-2
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-23 上午09:20:01        wangzhize     1.0            Initial Version
 * 2011-9-28 下午05:30:00        wangzhize     1.1     增加方法 validateDeleteRole，验证角色是否可被删除
 *****************************************************************************/
package com.cap.bts.framework.dm.userperm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cap.bts.framework.dm.userperm.service.IUserPermFuncService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.menu.service.IMenuService;
import com.cap.bts.framework.tree.Node;
import com.cap.bts.framework.usermgnt.domain.Role;
import com.cap.bts.framework.usermgnt.dto.RoleAndFunctionsDto;
import com.cap.bts.framework.usermgnt.dto.RoleDto;
import com.cap.bts.framework.usermgnt.dto.RoleQueryDto;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;

/**
 * RoleAndFunctionController
 */
@Controller
@RequestMapping(value = "/dm/userperm/rolefunc")
public class RoleAndFunctionController extends BaseController {
    private static Logger logger = Logger.getLogger(RoleAndFunctionController.class);

    @Autowired
    private IUserMgntService userMgntService;
    
    @Autowired
    private IUserPermFuncService userPermFuncService;

    @Autowired
    private IMenuService menuService;

    /**
     * 设置用户角色和权限
     * @Date        :      2011-12-8
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("roleQueryDto", new RoleQueryDto());
        model.addAttribute("initPage", true);
        return "/dm/userPerm/rolefunc/list";
    }

    /**
     *  query Roles with paging
     * @Date        :      2011-6-23
     * @param roleQueryDto
     * @param model
     * @param session
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public String queryRolesWithPaging(RoleQueryDto roleQueryDto, Model model, HttpSession session)
        throws AppException {

        model.addAttribute("roleList", userMgntService.queryRolesDtoWithPaging(roleQueryDto,true));
        model.addAttribute(CommonConstants.REQUEST_ATTRIBUTE_PAGER, roleQueryDto.getPager());
        model.addAttribute("roleQueryDto", roleQueryDto);
        session.setAttribute("roleQueryDto", roleQueryDto);
        return "/dm/userPerm/rolefunc/list";
    }

    /**
     * to edit role page
     * 
     * @Date : 2011-6-23
     * @param roleId
     * @param model
     *            Model
     * @return jsp page
     * @throws AppException
     *             the appException
     */
    @RequestMapping(value = "/edit/{roleId}", method = RequestMethod.GET)
    public String editRoleAndFunctions(@PathVariable("roleId") long roleId, Model model)
        throws AppException {
        RoleAndFunctionsDto rfdto = userMgntService.getRoleAndMenus(roleId);
        model.addAttribute("roleAndFunctionsDto", rfdto);
        return "/dm/userPerm/rolefunc/update_pre";
    }

    /**
     * to edit role page
     * 
     * @Date : 2011-6-23
     * @param roleId
     * @param model
     *            Model
     * @return jsp page
     * @throws AppException
     *             the appException
     */
    @RequestMapping(value = "/detail/{roleId}", method = RequestMethod.GET)
    public String getDetailRoleAndFunctions(@PathVariable("roleId") long roleId, Model model)
        throws AppException {
        RoleAndFunctionsDto rfdto = userMgntService.getRoleAndMenus(roleId);
        model.addAttribute("roleAndFunctionsDto", rfdto);
        return "/dm/userPerm/rolefunc/detail";
    }

    /**
     * to delete role page
     * @Date        :      2011-9-28
     * @param roleId
     * @param model
     * @param res
     * @return
     * @throws AppException
     * @throws IOException
     */
    @RequestMapping(value = "/delete/{roleId}", method = RequestMethod.GET)
    public String deleteRoleById(@PathVariable("roleId") long roleId, Model model,
        HttpServletResponse res) throws AppException,IOException {
        res.setCharacterEncoding("UTF-8");
        PrintWriter print = res.getWriter();
        boolean result = false;
        try {
        	result = userPermFuncService.deleteRoleById(Long.valueOf(roleId));
        } catch (AppException e){
        	throw e;
        } finally{
        	print.print(result);
            print.close();
        } 
        return null;
    }

    /**
     * 验证角色可否被删除
     * @Date        :      2011-9-28
     * @param roleId
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/validateDelRole/{roleId}")
    @ResponseBody
    public boolean validateDeleteRole(@PathVariable("roleId") long roleId) throws AppException {
        return userPermFuncService.validateDeleteRole(roleId);
    }
    /**
     * 查询menus
     * for regionType is embeded in a shared file-->dmstree.js, so here use
     * value=regiontype
     * @Date        :      2011-9-28
     * @param menuType
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/queryMenus")
    @ResponseBody
    public List<Node> queryMenus(@RequestParam(value = "regionType") int menuType)
        throws AppException {
        logger.debug("==================== querying menu tree ====================");
        logger.debug("parameter: [menuType = " + menuType + "]");
        List<Node> menus = menuService.getMenuNodesByRootType(menuType);
        logger.debug("==================== queryed menu tree successful " + "====================");
        return menus;

    }
    /**
     * update role to db
     * @Date        :      2011-9-28
     * @param roleAndFunctionsDto
     * @param request
     * @param model
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateRoleAndFunctions(RoleAndFunctionsDto roleAndFunctionsDto,
        HttpServletRequest request, Model model) throws AppException {
        // userMgntService).updateRoleAndFunctions(roleAndFunctionsDto);
        roleAndFunctionsDto.setLastAuthorizedBy(getCurrentUser()==null ? 0L : getCurrentUser().getId());
        userPermFuncService.updateRoleAndFunctions(roleAndFunctionsDto);
        HttpSession sess = request.getSession();
        RoleQueryDto roleQueryDto = (RoleQueryDto)(sess.getAttribute("roleQueryDto"));   
        return queryRolesWithPaging(roleQueryDto, model, sess);
    }

    /**
     * 验证是否存在此code
     * @Date        :      Dec 4, 2011
     * @param roleCode
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/validateCode")
    @ResponseBody
    public boolean validateCode(@RequestParam("roleCode") String roleCode,
        Model model, HttpServletRequest request) throws AppException { 
    	Role role = userMgntService.getRoleByCode(roleCode);
    	boolean valid = false;
    	if (role == null){
    		valid = true;
    	}
        return valid;
    }
    /**
     * enter create page 
     * @Date        :      2011-9-28
     * @param model
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/add")
    public String addRoleAndFunctionsPre(Model model) throws AppException {
        RoleAndFunctionsDto roleAndFunctionsDto = new RoleAndFunctionsDto();
        model.addAttribute("roleAndFunctionsDto", roleAndFunctionsDto);
        return "dm/userPerm/rolefunc/create_pre";
    }

    /**
     * save a new role to db
     * @Date        :      2011-9-28
     * @param roleAndFunctionsDto
     * @param request
     * @param model
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String addRoleAndFunctions(RoleAndFunctionsDto roleAndFunctionsDto,
        HttpServletRequest request, Model model) throws AppException {
        roleAndFunctionsDto.setIsDeleted(0);
        roleAndFunctionsDto.setLastAuthorizedBy(getCurrentUser()==null ? 0L : getCurrentUser().getId());
        roleAndFunctionsDto.setBrandId(0l);
        userPermFuncService.createRolesAndFunctions(roleAndFunctionsDto);
        
        HttpSession sess = request.getSession();
        RoleQueryDto roleQueryDto = new RoleQueryDto();    
        return queryRolesWithPaging(roleQueryDto, model, sess);

    }
    

}
